<template>
  <div class="follow-page">
    <div v-if="isPreview == 1" class="preview-z" />
    <div v-if="showType == 1">
      <div class="follow-main mb30">
        {{ followData.title || '' }}
      </div>
      <div class="f30 text-gray3 mb30">
        {{ followData.descContent }}
      </div>    
      <div
        class="follow-form"
        v-for="(item,index) of followData.topicChild"
        :key="index"
      >
        <div>
          <span v-if="item.type != 3 && item.type != 4" :class="item.mustAnswerStatus && item.type != 3 && item.type != 4 ? 'required' : ''"> {{ item.index ? item.index+'、' : '' }}</span><span>{{ item.type == 3 ? item.remarks : item.title }}</span><span class="text-gray6" v-if="item.type != 3 && item.type != 4">（{{ typeForm[item.type] }}）</span>
        </div>
        <div v-for="(val,valIndex) of item.itemChild" :key="valIndex">
          <!-- 单选 -->
          <div v-if="item.type == 0">
            <div class="follow-list" @click="radioClick(item.itemChild,val)">
              <van-radio :checked="(val.itemId == val.itemCloneId) || val.answerStatus">
                {{ val.title || '' }}
              </van-radio>
            </div>
            <div v-if="(val.blanks && (val.itemId == val.itemCloneId|| val.explan))" :class="val.mustAnswerStatus ? 'required' : ''">
              <van-field
                class="explain"
                v-model="val.explan"
                placeholder="请输入原因"
                :rules="[{ required: true, message: '请输入原因' }]"
              />
            </div>
          </div>
          <!-- 多选 -->
          <div v-if="item.type == 1">
            <div class="follow-list" @click="checkBoxClick(val)">
              <van-checkbox :checked="(val.itemId == val.itemCloneId) || val.answerStatus" shape="square">
                {{ val.title || '' }}
              </van-checkbox>
            </div>
            <div v-if="(val.blanks && (val.itemId == val.itemCloneId|| val.explan)) " :class="val.mustAnswerStatus ? 'required' : ''">
              <van-field
                class="explain"
                v-model="val.explan"
                placeholder="请输入原因"
                :rules="[{ required: true, message: '请输入原因' }]"
              />
            </div>
          </div>
        </div>
        <!-- 问答题 -->
        <div v-if="item.type == 2">
          <van-field
            v-if="isPreview != 1"
            class="follow-text"
            v-model="item.explan"
            rows="2"
            autosize
            type="textarea"
            maxlength="500"
            placeholder="请输入"
            show-word-limit
          />
          <!-- 这里数据格式有点问题，因为简答题就只有一项 -->
          <div
            v-else
            v-for="(val,valIndex) of item.itemChild"
            :key="valIndex"
          >
            <van-field
              class="follow-text"
              v-model="val.explan"
              rows="2"
              autosize
              type="textarea"
              maxlength="500"
              placeholder="请输入"
              show-word-limit
            />
          </div>
        </div>
      </div>
      <van-button
        v-if="isPreview != 1"
        type="primary"
        block
        class="mt30"
        color="#20beb6"
        @click="submit"
      >
        提交
      </van-button>
      <div class="h40" />
      <div />
    </div>
   
    <div v-else>
      <div class="flex flex-center flex-column">
        <div class="box-main flex flex-center">
          <div class="right-box flex flex-center">
            <van-icon name="success" />
          </div>
        </div>
        <div class="sub-title text-bold">
          提交成功
        </div>
        <div class="tips-title text-gray3">
          您已填写完成【{{ followForm[followData.type] }}】
        </div>
        <div
          v-if="fromType != 0"
          class="tips-title text-gray3 tianxie-answer"
          @click="checkAnswer"
        >
          查看填写结果
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useService } from '@/utils/services';
import { Toast } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { Dialog } from 'vant';
export default {
  setup() {
    let typeForm = {
      0: '单选',
      1: '多选',
      2: '问答题',
      3: '段落说明'
    };

    let followForm = {
      0: '随访单',
      1: '考试问卷',
      2: '满意度调查问卷'
    };

    let throttle = ref(true);

    const route = useRoute();
    const questionId = route.query.questionId;
    const planDetailId = route.query.planDetailId || ''; //推送计划详情id
    const fromType = route.query.fromType; //问卷来源类型 0小程序首页，1患者群发（计划），2智能推送,3离院自动推送
    const isPreview = ref(route.query.isPreview);
    const entry = route.query.entry;
    const messageId = route.query.messageId || '';
    const followData = ref({});
    const actions = useService();
    const showType = ref(1); //1还没答题，2已经答完了
    const answerTime = ref(); //停留时间
    const router = useRouter();

    function getNowTime() {
      answerTime.value = Date.parse(new Date());
    }
    getNowTime();

    //获取问卷详情
    function getQuestionInfo() {
      let url = isPreview.value == 1 ? 'getQuestionPreviewInfo' : 'getQuestionInfo';
      actions.hos[url]({ questionId: questionId, planDetailId: planDetailId }).then((res) => {
        followData.value = res || {};
        document.title = followForm[followData.value.type];
        changeData();
        if (isPreview.value !== 1) {
          showType.value = res.answerStatus && fromType != 0 ? 2 : 1; //除首页外，其它地方进来的，都只能填一次问卷
        }
        if (res.withdrawStatus) {
          return withdraw();
        }
      });
    }
    if (questionId) {
      getQuestionInfo();
    }

    const withdraw = () => {
      Dialog.confirm({
        message: '该问卷已撤回',
        showCancelButton: false
      }).then(() => {
        if (entry) {
          router.push('/home');
        } else {
          router.back();
        }
      });
    };

    //查看答案
    function checkAnswer(type) {
      showType.value = 1;
      isPreview.value = 1;
      let url = type == 'answer' ? 'getQuestionPreviewInfo' : 'getQuestionInfo';
      actions.hos[url]({ questionId: questionId || '', planDetailId: planDetailId }).then((res) => {
        if (res.withdrawStatus) {
          return withdraw();
        }
        followData.value = res.answerResponse || res; //在科室小程序，有的时候患者还未答题，就取res
        let bIndex = 0;
        followData.value.topicChild.forEach((item) => {
          if (item.title) {
            bIndex++;
            item.bIndex = bIndex;
          }
        });
      });
    }

    if (planDetailId && !questionId) {
      //患者端小程序查看问卷填写过得答案，不会带questionId过来，只需要传一个planDetailId
      checkAnswer('answer');
    }

    //改造数据
    function changeData() {
      let bIndex = 0;
      if (!followData.value.topicChild || followData.value.topicChild.length == 0) {
        return;
      }
      followData.value.topicChild.forEach((item) => {
        if (item.title) {
          bIndex++;
          item.bIndex = bIndex;
        }
        if (item.type == 2) {
          //简答题，直接放个答案
          item.explan = '';
        } else if (item.type == 0 || item.type == 1) {
          //单选和多选题，每一项都要加上是否被选中了以及选项填空需要保存的字段
          item.itemChild.forEach((val) => {
            val.explan = ''; //选项填空需要绑定的字段
            val.itemCloneId = ''; //被选中的选项id
          });
        }
      });
    }

    //单选，选择
    function radioClick(item, val) {
      item.forEach((item) => {
        item.itemCloneId = '';
      });
      val.itemCloneId = val.itemId;
    }

    //多选，选择
    function checkBoxClick(val) {
      val.itemCloneId = val.itemCloneId == val.itemId ? '' : val.itemId;
    }

    //终极提交
    function submit() {
      let topicList = [];
      let flag = true;
      followData.value.topicChild.forEach((item) => {
        let answerRequestList = [];
        if (item.type === 0 || item.type === 1) {
          item.itemChild.forEach((val) => {
            if (val.itemCloneId) {
              if (val.mustAnswerStatus && val.blanks && !val.explan) {
                //选项填空未必填
                flag = false;
              }
              answerRequestList.push({ explan: val.explan, itemId: val.itemCloneId });
            }
          });
          if (item.mustAnswerStatus && answerRequestList.length == 0) {
            //未必填
            flag = false;
          }
          topicList.push({ answerRequestList: answerRequestList, topicId: item.topicId });
        } else if (item.type === 2) {
          if (item.mustAnswerStatus && !item.explan) {
            //简答题未必填
            flag = false;
          }
          // itemId:item.itemChild[0].itemId
          topicList.push({
            answerRequestList: [{ explan: item.explan, itemId: item.itemChild[0].itemId }],
            topicId: item.topicId
          });
        }
      });

      if (!flag) {
        Toast('请检查必填项！');
        return;
      }

      let stopTime = (Date.parse(new Date()) - answerTime.value) / 1000;
      let form = {
        fromType: fromType, //问卷来源类型0，小程序1首页，1患者群发（计划），2智能推送,3离院自动推送
        planDetailId: planDetailId, //推送计划详情id
        questionId: questionId, //问卷主键
        topicList: topicList,
        answerTime: stopTime, //停留时长
        messageId: messageId
      };

      if (!throttle.value) {
        return;
      }

      throttle.value = false;
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '提交中...'
      });
      actions.hos
        .saveQuestionAnswer(form)
        .then((res) => {
          showType.value = 2;
        })
        .finally(() => {
          toast.clear();
          throttle.value = true;
        });
    }
    return {
      followData,
      typeForm,
      radioClick,
      checkBoxClick,
      submit,
      showType,
      followForm,
      answerTime,
      isPreview,
      checkAnswer,
      planDetailId,
      fromType
    };
  }
};
</script>

<style lang="scss" scoped>
.follow-page {
  min-height: 100vh;
  padding: 20px 32px 0;
  background: #fff;
  position: relative;
}
.follow-main {
  color: #20beb6 !important;
  font-size: 40px;
}
.f30 {
  font-size: 30px;
}
.follow-form {
  font-size: 34px;
  margin-top: 40px;
  padding-bottom: 30px;
}
.follow-list {
  height: 100px;
  padding-left: 30px;
  width: 100%;
  border: 1px solid #ccc;
  margin-top: 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
}
.explain {
  border: 1px solid #ccc;
  margin-top: 5px;
  height: 70px;
  padding: 10px 20px;
}
.follow-text {
  border: 1px solid #ccc;
  border-radius: 10px;
}
.h40 {
  height: 40px;
}
.box-main {
  width: 220px;
  height: 220px;
  margin-top: 20%;
  background: rgba(32, 190, 182, 0.1) !important;
  border-radius: 100%;
}
.right-box {
  width: 170px;
  height: 170px;
  background: #20beb6 !important;
  border-radius: 100%;
  color: #fff;
  font-size: 90px;
}
.sub-title {
  color: #20beb6 !important;
  font-size: 36px;
  margin-top: 32px;
}
.tips-title {
  font-size: 28px;
  margin-top: 17%;
}
.preview-z {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
}
.tianxie-answer {
  position: absolute;
  bottom: 150px;
  color: #20beb6;
}
</style>